package com.orangelife.mobile.lookRepair.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.IXListViewListener;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.lookRepair.adapter.LookForRepairListAdapter;
import com.orangelife.mobile.lookRepair.adapter.LookForRepairListAdapter.AdapterListenter;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 维修列表 yyx
 */
public class LookForRepairListActivity extends OrangeLifeBaseActivity {

    /**
     * 标题中间
     */
    private TextView tvTitle;
    /**
     * 标题右边
     */
    private TextView tvTitleRight;
    /**
     * 列表
     */
    private PullToRefreshListView lvList;
    /**
     * listview上面的横线
     */
    private View view;
    /**
     * 无订单
     */
    private LinearLayout llNoBill;
    /**
     * 返回顶部
     */
    private Button btnTop;
    /**
     * 分辨是刷新还是加载更多
     */
    private int flags = 1;
    /**
     * 一页中数据的条数，初始设置为7条
     */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /**
     * 初始页，初始化为第一页
     */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    private Dialog dialog;
    private LookForRepairListAdapter<Map<String, Object>> adapter;
    private Handler mHandler;
    private List<Map<String, Object>> list;
    private List<Map<String, Object>> list2;
    private boolean scrollFlag = false;// 标记是否滑动
    private int lastVisibleItemPosition = 0;// 标记上次滑动位置
    /**
     * 无订单
     */
    private View selectView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lookfor_repair_list);
        initeView();
        getRepairRead();
    }

    @Override
    protected void onResume() {
        super.onResume();
        findView();
        closeActivity();
    }

    /**
     * 初始化
     */
    private void initeView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitleRight = (TextView) findViewById(R.id.tv_title_right);
        lvList = (PullToRefreshListView) findViewById(R.id.lvRepair);
        view = (View) findViewById(R.id.view);
        btnTop = (Button) findViewById(R.id.top_btn);
    }

    /**
     * 赋值
     */
    private void findView() {
        tvTitle.setText(R.string.my_repair);
        mHandler = new Handler();

        getDataFromServer();
        pageNo = 1;
        getRepairList(pageSize, pageNo);
        setAdapter();
        lvList.setPullLoadEnable(false);
        lvList.setAdapter(adapter);
        pullListView();
//		initNoBill();
        btnTop.setOnClickListener(listener);
        lvList.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
                        scrollFlag = false;
                        // 判断滚动到底部
                        if (lvList.getLastVisiblePosition() == (lvList
                                .getCount() - 1)) {
                            btnTop.setVisibility(View.VISIBLE);
                        }
                        // 判断滚动到顶部
                        if (lvList.getFirstVisiblePosition() == 0) {
                            btnTop.setVisibility(View.GONE);
                        }

                        break;
                    case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
                        scrollFlag = true;
                        break;
                    case OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
                        scrollFlag = true;
                        break;
                }
            }

            /**
             * firstVisibleItem：当前能看见的第一个列表项ID（从0开始）
             * visibleItemCount：当前能看见的列表项个数（小半个也算） totalItemCount：列表项共数
             */
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 当开始滑动且ListView底部的Y轴点超出屏幕最大范围时，显示或隐藏顶部按钮
                if (firstVisibleItem > 0) {
                    btnTop.setVisibility(View.VISIBLE);
                } else {
                    btnTop.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * 无订单
     */
    private void initNoBill() {
        selectView = getLayoutInflater().inflate(R.layout.include_repair_no_bill, null);
        llNoBill = (LinearLayout) selectView.findViewById(R.id.llNoBill);
        lvList.addHeaderView(selectView);
    }

    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.top_btn:
                    setListViewPos(0);
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 滚动ListView到指定位置
     *
     * @param pos
     */
    private void setListViewPos(int pos) {
        if (android.os.Build.VERSION.SDK_INT >= 8) {
            lvList.smoothScrollToPosition(pos);
        } else {
            lvList.setSelection(pos);
        }
    }

    /**
     * 设置适配器
     */
    private void setAdapter() {
        list = new ArrayList<Map<String, Object>>();
        list2 = new ArrayList<Map<String, Object>>();
        adapter = new LookForRepairListAdapter<Map<String, Object>>(this,
                list);
        adapter.setAdapterListener(new AdapterListenter() {

            @Override
            public void refresh(String str) {
                flags = 1;
                pageNo = 1;
                getRepairList(pageSize, pageNo);
            }
        });
        lvList.setPullLoadEnable(false);
        lvList.setAdapter(adapter);
    }

    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvList.setXListViewListener(new IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        getRepairList(pageSize, pageNo);
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        getRepairList(pageSize, pageNo);
                        onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    private void updateListView(List<Map<String, Object>> list2) {
        if (list2 == null) {
            lvList.setPullLoadEnable(false);
            if (flags == 1) {
                list.clear();
                adapter.setList(list);
                adapter.notifyDataSetChanged();
            }
        }
        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                if (flags == 1) {
                    list.clear();
                    lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
//					view.setVisibility(View.GONE);
//					llNoBill.setVisibility(View.VISIBLE);
                } else {
                    lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            } else {
//				view.setVisibility(View.VISIBLE);
//				llNoBill.setVisibility(View.GONE);
                if (flags == 1) {
                    list.clear();
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                } else {
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            }
        } else {
            lvList.setPullLoadEnable(false);
            if (flags == 1) {
//				view.setVisibility(View.GONE);
//				llNoBill.setVisibility(View.VISIBLE);
            }
        }
    }


    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    /**
     * 获取列表数据
     *
     * @param pageSize 每页的条数
     * @param pageNo   初始页
     */
    private void getRepairList(int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageIndex", pageNo);
        map.put("pageSize", pageSize);
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", map);
        rootMap.put("url", Constant.URL_LOOKREAPIR_LIST);
        rootMap.put("wat", 0);
        new JSONRequest(JSONRequest.POST, rootMap, handler, HttpUtil.ACTION_JSON);
    }

    /**
     * 处理获得的数据
     */
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    list2 = JsonReponseHandler.getListFromJson(
                            String.valueOf(msg.obj), adapter, dialog);

                    updateListView(list2);
                    break;
                case 4:
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    if (errInfo.equals("OK")) {
                        Log.e("errInfo", "success");
                    } else {
                        Log.e("errInfo", "fail");
                    }
                    break;
                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog);
                    break;

                default:
                    break;
            }
        }

    };


    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvList.stopRefresh();
        lvList.stopLoadMore();
        lvList.setRefreshTime(new Date().toLocaleString());
    }

    /**
     * 维修列表消息状态改为已读
     */
    private void getRepairRead() {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, Constant.URL_REPAIR_READ, map, handler, 4, HttpUtil.ACTION_URI);
    }

    /**
     * 返回
     */
    @Override
    public void onBackClick(View v) {
        super.onBackClick(v);
        CurryApplication.getInstance().setUpdate(false);
        finish();
    }

}
